import { defineStore } from 'pinia';

import { usePermissionStore } from '@/store';
import type { UserInfo } from '@/types/interface';
import { loginPwd,currentUser } from '@/api/login';
import router from '@/router';
const InitUserInfo: UserInfo = {
  name: '', // 用户名，用于展示在页面右上角头像处
  roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: 'main_token', // 默认token不走权限
    tokenHead:'Authorization',
    userInfo: { ...InitUserInfo },
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
  },
  actions: {
    async login(userInfo: { username?: string; email?: string; phone?: string; password: string }) {
      try {
        const response = await loginPwd(userInfo);
        this.token = response.token;
        this.tokenHead = response.tokenHead;
        // 获取用户信息
        this.userInfo = await currentUser();
        const permissionStore = usePermissionStore();
        permissionStore.getPerms();
      } catch (error) {
        console.error('登录失败:', error);
        throw error;
      }
    },
    async getUserInfo() {
      
      this.userInfo = await currentUser();
      const permissionStore = usePermissionStore();
      permissionStore.getPerms();

    },
    async logout() {
      this.token = '';
      this.userInfo = { ...InitUserInfo };
    },
  },
  
  persist: {
    afterRestore: () => {
      const permissionStore = usePermissionStore();
      permissionStore.initRoutes();
      
    },
    key: 'user',
    paths: ['token'],
  },
});
